<?php
/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2019/5/15
 * Time: 15:59
 */

namespace app\admin\logic;
use app\common\model\Site;
use app\common\model\User;
use app\common\model\SiteTeam;
use app\common\model\Organization;
use app\admin\logic\code\ErrorCode;
use app\vehicle\model\Volunteer;
use app\vehicle\logic\TplLogic;
class VolunteersLogic extends BaseLogic
{

    private $VolunteerModel;

    public function __construct()
    {
        parent::__construct();
        $this->VolunteerModel = new Volunteer();

    }

    public function PartyList($tempWhere, $nowPage){
        $where[] = ['is_party', 'eq', 1];
        if ($tempWhere['nick_name']){
            $where[] = ['realname', 'LIKE', "%".$tempWhere['nick_name']."%"];
        }
        if (is_numeric($tempWhere['status'])){
            $where[] = ['status', 'eq', $tempWhere['status']];
        }
        if (is_numeric($tempWhere['o_status'])){
            $where[] = ['o_status', 'eq', $tempWhere['o_status']];
        }
        if (is_numeric($tempWhere['site_id'])){
            $where[] = ['site_id', 'eq', $tempWhere['site_id']];
        }
        if (is_numeric($tempWhere['site_ids'])){
            $where[] = ['site_id', 'eq', $tempWhere['site_ids']];
        }
//        $oid = $_SESSION['xm_travel']['admin_info']['oid'];
//        $site_id = $_SESSION['xm_travel']['admin_info']['site_id'];
//        if($oid){
//            $where[] = ['oid', 'eq', $oid];
//        }else if($site_id){
//            $where[] = ['site_id', 'eq', $site_id];
//        }

        $count = $this->VolunteerModel->where($where)->where(function ($query){
            $oid = $_SESSION['xm_travel']['admin_info']['oid'];
            $site_id = $_SESSION['xm_travel']['admin_info']['site_id'];
            if($oid){
                $num = db('site_team')->where('oid','=',$oid)->count();
                if($num) {
                    $allid = implode(',', db('site_team')->where('oid', '=', $oid)->column('id'));
                    $w[] = ['oid', 'in', $oid . ',' . $allid];
                }else{
                    $w[] = ['oid','=',$oid];
                }
                $query->where($w);
            }else if($site_id) {
                if (db('site')->where('sid', '=', $site_id)->count() ) {
                    $allid = implode(',', db('site')->where('sid', '=', $site_id)->column('id'));
                    $w[] = ['site_id', 'in', $site_id . ',' . $allid];
                    $query->where($w);
                } else {
                    $w[] = ['site_id', 'eq', $site_id];
                    $query->where($w);
                }
            }
        })->count();
        $list = $this->VolunteerModel->with(['user','site_name','teams'])->hidden(['password'])->order('create_time desc')->where($where)->where(function ($query){
            $oid = $_SESSION['xm_travel']['admin_info']['oid'];
            $site_id = $_SESSION['xm_travel']['admin_info']['site_id'];
            if($oid){
                $num = db('site_team')->where('oid','=',$oid)->count();
                if($num) {
                    $allid = implode(',', db('site_team')->where('oid', '=', $oid)->column('id'));
                    $w[] = ['oid', 'in', $oid . ',' . $allid];
                }else{
                    $w[] = ['oid','=',$oid];
                }
                $query->where($w);
            }else if($site_id) {
                if (db('site')->where('sid', '=', $site_id)->count() ) {
                    $allid = implode(',', db('site')->where('sid', '=', $site_id)->column('id'));
                    $w[] = ['site_id', 'in', $site_id . ',' . $allid];
                    $query->where($w);
                } else {
                    $w[] = ['site_id', 'eq', $site_id];
                    $query->where($w);
                }
            }
        })->page($nowPage,$tempWhere['limit'])->select();
        if ($count > 0){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $list, $count);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '列表为空');
        }
    }
    public function VolunteerList($tempWhere, $nowPage){
        $where[] = ['is_after', '=',$tempWhere['is_after']];
        if ($tempWhere['nick_name']){
            $where[] = ['realname', 'LIKE', "%".$tempWhere['nick_name']."%"];
        }
        if (is_numeric($tempWhere['status'])){
            $where[] = ['status', 'eq', $tempWhere['status']];
        }
        if (is_numeric($tempWhere['o_status'])){
            $where[] = ['o_status', 'eq', $tempWhere['o_status']];
        }
        if (is_numeric($tempWhere['site_id'])){
            $where[] = ['site_id', 'eq', $tempWhere['site_id']];
        }
        if (is_numeric($tempWhere['oid'])){
            $where[] = ['oid', 'eq', $tempWhere['oid']];
        }
        if (is_numeric($tempWhere['site_ids'])){
            $where[] = ['site_id', 'eq', $tempWhere['site_ids']];
        }
        if ($tempWhere['mobile']){
            $where[] = ['mobile', 'like', '%'.$tempWhere['mobile'].'%'];
        }
        $count = $this->VolunteerModel->where($where)->where(function ($query){
            $oid = $_SESSION['xm_travel']['admin_info']['oid'];
            $site_id = $_SESSION['xm_travel']['admin_info']['site_id'];
            if($oid){
                $num = db('site_team')->where('oid','=',$oid)->count();
                if($num) {
                    $allid = implode(',', db('site_team')->where('oid', '=', $oid)->column('id'));
                    $w[] = ['oid', 'in', $oid . ',' . $allid];
                }else{
                    $w[] = ['oid','=',$oid];
                }
                $query->where($w);
            }else if($site_id) {
                if (db('site')->where('sid', '=', $site_id)->count() ) {
                    $allid = implode(',', db('site')->where('sid', '=', $site_id)->column('id'));
                    $w[] = ['site_id', 'in', $site_id . ',' . $allid];
                    $query->where($w);
                } else {
                    $w[] = ['site_id', 'eq', $site_id];
                    $query->where($w);
                }
            }
        })->count();
        $list = $this->VolunteerModel
            ->with(['user','site_name','teams'])->hidden(['password'])
            ->order('nums desc,create_time desc')
            ->where($where)
            ->where(function ($query){
                $oid = $_SESSION['xm_travel']['admin_info']['oid'];
                $site_id = $_SESSION['xm_travel']['admin_info']['site_id'];
                if($oid){
                    $num = db('site_team')->where('oid','=',$oid)->count();
                    if($num) {
                        $allid = implode(',', db('site_team')->where('oid', '=', $oid)->column('id'));
                        $w[] = ['oid', 'in', $oid . ',' . $allid];
                    }else{
                        $w[] = ['oid','=',$oid];
                    }
                    $query->where($w);
                }else if($site_id) {
                    if (db('site')->where('sid', '=', $site_id)->count() ) {
                        $allid = implode(',', db('site')->where('sid', '=', $site_id)->column('id'));
                        $w[] = ['site_id', 'in', $site_id . ',' . $allid];
                        $query->where($w);
                    } else {
                        $w[] = ['site_id', 'eq', $site_id];
                        $query->where($w);
                    }
                }
            })
            ->page($nowPage,$tempWhere['limit'])->select();
        foreach($list as $k=>$v){
            if(!$v['thumb'] && $v['is_after']==1){
                include_once "../vendor/QrcodeService.php";
                $path = '/uploads/qrcode/volunteer/'.$v['id'].'.png';
                $url = $v['id'];
                \QRcode::png($url, '.'.$path, 'H',20, 1);
                $list[$k]['thumb'] = $path;
                $this->VolunteerModel->where('id','=',$v['id'])->update(['thumb'=>$path]);
            }
        }
        if ($count > 0){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $list, $count);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '列表为空');
        }
    }

    public function getcode($order_id){
        $APPID='wx0ddf18de26ea6f90';
        $AppSecret='9e85e33eaff1c91418f8f8506bdaaba5';
        $qrpath='qrcode'; //路径在public文件夹里面
        if(!is_dir('.'.$qrpath)){                              //  /public/qrcode/
            mkdir(iconv("GBK","UTF-8",'.'.$qrpath),0777,true);
        }
        $file = $qrpath.'/'.$order_id;
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        //获取access_token
        $access = json_decode($this->get_access_token($APPID,$AppSecret),true);
        $access_token= $access['access_token'];
        $url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=?access_token=".$access_token;
        //传递参数，用$user_id区分每个用户生成的二维码
        $listdata=[
            'path'=>'pages/passbook/index?scene='.$order_id
        ];
        $listdata=json_encode($listdata);
        $result=$this->api_notice_increment($url,$listdata);
        if (!$result) {
            return false;
        }
        arr($result);die;
        //查询是否存在二维码
        $list='';
        if(empty($list['qrcode'])){
            $res = file_put_contents("uploads/qrcode/volunteer/".$order_id.".jpg", $result);
            //  将获取到的二维码图片流保存成图片文件
            if($res===false) return json_encode(array('status'=>0,'info'=>'生成二维码失败','res'=>$res));
            $filename="uploads/qrcode/volunteer/".$order_id.".jpg";//用id编号当二维码名称
            $datafile=['qrcode'=>$filename];
            $this->VolunteerModel->where('id','eq',$order_id)->update(['thumb'=>'/'.$filename]);
            return '/'.$filename;
        }else{
            return '';
        }
    }

    public function api_notice_increment($url, $data){
        $curl = curl_init();
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }else{
            return $tmpInfo;
        }
    }
    public function get_access_token($APPID,$AppSecret){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$AppSecret;
        return $data = $this->curl_get($url);
    }
    public function curl_get($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        return $data;
    }

    public function userIntegral($data,$nowPage){
        $where = '';
        $role = session('admin_info');
        if($data['id']){
            $where['user_id'] = $data['id'];
        }
        if($role['role_id']==3) {
            $where['user_id'] = $role['shop_id'];
        }
        $count = $this->integralModel->where($where)->count();
        $list = $this->integralModel->where($where)->page($nowPage, self::$pageNum)->select();
        foreach($list as $k=>$v){
            $user = $this->VolunteerModel->where('id','eq',$v['user_id'])->find();
            $list[$k]['head_pic'] = $user['head_pic'];
            $list[$k]['nick_name'] = $user['nick_name'];
            $type = $v['type_id']==1?'-':'+';
            $list[$k]['integral'] = $type.$v['integral'];
        }
        if ($count > 0){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $list, $count);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '列表为空');
        }
    }

    public function VolunteerInfo($id){
        $userInfo =  Volunteer::field('*,status as sid')->where('id','eq',$id)->find();
        if ($userInfo){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $userInfo);
        } else{
            return ajaxArr(ErrorCode::$INFONULL, '该信息不存在');
        }
    }

    /**
     * 用户编辑
     * @param $data
     * @return mixed
     */
    public function handle($data){
        $act = $data['act'];
        unset($data['act']);
        $res = false;
        switch ($act){
            case 'add':
                $check = Volunteer::where('mobile','=',$data['mobile'])->count();
                if($check){
                    return ajaxArr(ErrorCode::$OPERATIONERROR, '该手机号已存在');
                }

                $id = User::insertGetId([
                    'nick_name'=>$data['realname'],
                    'mobile'=>$data['mobile'],
                    'create_time'=>time()
                ]);
                $data['user_id'] = $id;
                $data['is_after'] = 1;
                $data['nums'] = str_pad(db('volunteer_num')->order('id desc')->value('id')+1,6,'0',STR_PAD_LEFT);
                $data['create_time'] = time();
                $res = $this->VolunteerModel->allowField(true)->save($data);
                break;
            case 'examine':
                $list = Volunteer::where('id','in',$data['ids'])->select();
                foreach($list as $k=>$v){
                    $info = $v;
                    $openid = User::where('id','eq',$info['user_id'])->value('open_id');
                    $val = '审核通过,请绑定站点';
                    $result = $val;
                    $title = '志愿者申请';
                    $up['status'] = 1;
                    if($info['new_oid']){
                        $title = '组织绑定';
                        $result = '认证通过';
                        $up['o_status'] = 1;
                        $up['oid'] = $info['new_oid'];
                    }
                    if($info['new_site_id']){
                        $title = '组织绑定';
                        $result = '认证通过';
                        $up['o_status'] = 1;
                        $up['site_id'] = $info['new_site_id'];
                    }
                    $openid && TplLogic::examineTpl($openid,$title,$result);

                    $res = Volunteer::where('id','eq',$v['id'])->update($up);
                }
                break;
            case 'edit':
                $info = Volunteer::get($data['id']);
                $openid = User::where('id','eq',$info['user_id'])->value('open_id');

                if($data['status']==1){
                    $val = '审核通过,请绑定站点';
                }else if($data['status']==2){
                    $val = '审核不通过';
                }
                if($data['o_status']==2){
                    $data['oid'] = 0;
                    $data['site_id'] = 0;
                    $vals = '认证不通过';
                }else if($data['o_status']==1){
                    $vals = '认证通过';
                }
                $result = $val;
                $title = '志愿者申请';
                if($data['oid']){
                    $title = '组织绑定';
                    $result = $vals;
                }
                $openid && TplLogic::examineTpl($openid,$title,$result);

                $res = Volunteer::update($data);
                break;
            case 'batch':
                if(is_numeric($data['number'])) {
                    if($data['number']>200){
                        return ajaxArr(ErrorCode::$OPERATIONERROR, '批量生成数量最多为200');
                    }
                    for($i=0;$i<$data['number'];$i++) {
                        $time = time();
                        $nums = str_pad(db('volunteer_num')->where('id','=',1)->value('num') + 1, 6, '0', STR_PAD_LEFT);
                        db('volunteer_num')->where('id','=',1)->setInc('num');
                        $insert = [
                            'create_time' => $time,
                            'is_after' => 1,
                            'nums' => $nums
                        ];
                        if($data['type_id']==1){
                            $insert['oid'] = $data['oid'];
                        }else{
                            $insert['site_id'] = $data['site_id'];
                        }
                        $res = Volunteer::insertGetId($insert);
                        include_once "../vendor/QrcodeService.php";
                        $path = '/uploads/qrcode/volunteer/' . $res . '.png';
                        $url = $res;
                        \QRcode::png($url, '.' . $path, 'H', 20, 1);
                        $res = Volunteer::where('id', '=', $res)->update(['thumb' => $path]);
                    }
                }else{
                    return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
                }
                break;
            case 'del':
                $res = Volunteer::where('id','=',$data['id'])->delete();
                break;
            default:
                break;
        }
        if ($res){
            return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
        } else{
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }

    public function auditHandle($data){
        $up['status'] = $data['status'];
        $res = UserInfo::where('id','eq',$data['id'])->update($up);
        if ($res){
            return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
        } else{
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }

}